package library.and.xps.com.step.view.activity;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.jude.utils.JUtils;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.OnClickListener;
import com.orhanobut.dialogplus.ViewHolder;
import com.orhanobut.logger.Logger;
import com.squareup.okhttp.Request;
import com.xyz.xruler.XyzRuler;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import jp.wasabeef.glide.transformations.CropCircleTransformation;
import library.and.xps.com.step.R;
import library.and.xps.com.step.URLConstants;
import library.and.xps.com.step.m.model.RequestParams;
import library.and.xps.com.step.m.model.UpdateUserInfo;
import library.and.xps.com.step.m.model.User;
import library.and.xps.com.step.m.netapi.OkHttpClientUtils;
import library.and.xps.com.step.net.ResponceWrapper;
import library.and.xps.com.step.util.CommonUtils;
import library.and.xps.com.step.util.HttpResponsHelper;
import library.and.xps.com.step.util.RequestCallback;
import library.and.xps.com.step.util.UserHelper;
import library.and.xps.com.step.view.base.BaseActivity;
import library.and.xps.com.step.view.customview.WheelView;

import static library.and.xps.com.step.view.activity.SetupUserNickameActivity.RESPONCECODE_CUSTOM_NICKNAME;

public class CustomPersonInfoActivity extends BaseActivity implements com.orhanobut.dialogplus.OnClickListener, TakePhoto.TakeResultListener, InvokeListener {
    ImageView iv_head, iv_back;
    TextView tv_name, tv_gender, tv_stature, tv_weight, tv_actionbar_title, tv_actionbar_right, tv_setp_perday;
    String user_stature;
    String user_weight;
    String dialog_showing;
    String step_plan;
    InvokeParam invokeParam;
    TakePhoto takePhoto;
    Uri imageUri;
    File file;
    static final int REQUESTCODE_CUSTOM_NICKNAME = 1;

    @Override
    protected int getLayout() {
        return R.layout.activity_custom_person;
    }

    @Override
    protected void setData() {
        User user = getUser();
        if (user ==null)return;

        JUtils.Log("CurrentUser:" + user.toString());
        tv_stature.setText(user.getStature() + "cm");
        tv_weight.setText(user.getWeight() + "kg");
        if (user.getSex().equals("0")) {
            tv_gender.setText("女");
        } else {
            tv_gender.setText("男");
        }

        tv_setp_perday.setText(user.getStepperday() + "步");
        tv_name.setText(user.getNickname());
        CommonUtils.setupCircleImg(this, iv_head, user.getIco());
    }

    @Override
    protected void init() {
        iv_head = r2v(R.id.iv_head);
        tv_name = r2v(R.id.tv_name);
        tv_gender = r2v(R.id.tv_gender);
        tv_stature = r2v(R.id.tv_stature);
        tv_weight = r2v(R.id.tv_weight);
        iv_back = r2v(R.id.actionbar_iv_back);
        tv_setp_perday = r2v(R.id.tv_setp_perday);
        tv_setp_perday.setOnClickListener(this);
        tv_actionbar_title = r2v(R.id.actionbar_tv_title);
        tv_actionbar_title.setText("用户信息");

        iv_head.setOnClickListener(this);
        tv_name.setOnClickListener(this);
        tv_gender.setOnClickListener(this);
        tv_stature.setOnClickListener(this);
        tv_weight.setOnClickListener(this);
        iv_back.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.iv_head:
                File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
                if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
                imageUri = Uri.fromFile(file);

                CompressConfig config = new CompressConfig.Builder()
                        .setMaxSize(102400)
                        .create();
                takePhoto.onEnableCompress(config, false);

                CropOptions.Builder builder = new CropOptions.Builder();
                builder.setAspectX(800).setAspectY(800);
                builder.setOutputX(800).setOutputY(800);
                builder.setWithOwnCrop(true);
                takePhoto.onPickFromGalleryWithCrop(imageUri, builder.create());
                break;
            case R.id.tv_gender:
                break;
            case R.id.tv_stature:
                dialog_showing = "tv_stature";
                showWeightDialog(this);
                break;
            case R.id.tv_weight:
                dialog_showing = "tv_weight";
                showStatureDialog();
                break;
            case R.id.actionbar_iv_back:
                finish();
                break;
            case R.id.tv_name:
                Intent intent = new Intent(this, SetupUserNickameActivity.class);
                intent.putExtra("nickname", tv_name.getText().toString());
                startActivityForResult(intent, REQUESTCODE_CUSTOM_NICKNAME);
                break;
            case R.id.tv_setp_perday:
                dialog_showing = "setp_perday";
                showStepPlanDialog();
                break;
        }
    }

    @Override
    public void onClick(DialogPlus dialog, View view) {
        dialog.dismiss();
        switch (view.getId()) {
            case R.id.footer_close_button:

                break;
            case R.id.footer_confirm_button:
                if (dialog_showing.equals("tv_weight")) {
                    tv_weight.setText(user_weight + "kg");
                    updateUserRequest("weight", user_weight);
                } else if (dialog_showing.equals("tv_stature")) {
                    tv_stature.setText(user_stature + "cm");
                    updateUserRequest("stature", user_stature);
                } else if (dialog_showing.equals("setp_perday")) {
                    tv_setp_perday.setText(step_plan);
                    updateUserRequest("goal", step_plan);
                }
                break;
        }
    }

    /**
     * 向服务器 请求修改用户信息
     * */
    void updateUserRequest(final String param, final String value) {
        JSONObject json = new JSONObject();
        if ("ico".equals(param)) {
            json = RequestParams.getNewInstance().setUserid(getUser().getUserid()).setIco(value).getJson();
        } else if ("sex".equals(param)) {
            json = RequestParams.getNewInstance().setUserid(getUser().getUserid()).setSex(value).getJson();
        } else if ("weight".equals(param)) {
            json = RequestParams.getNewInstance().setUserid(getUser().getUserid()).setWeight(value).getJson();
        } else if ("stature".equals(param)) {
            json = RequestParams.getNewInstance().setUserid(getUser().getUserid()).setStature(value).getJson();
        } else if ("nickname".equals(param)) {
            json = RequestParams.getNewInstance().setUserid(getUser().getUserid()).setNickname(value).getJson();
        } else if ("goal".equals(param)) {
            json = RequestParams.getNewInstance().setUserid(getUser().getUserid()).setGoal(value).getJson();
        }

        OkHttpClientUtils.postJsonStringAsync(this, URLConstants.USER.UpdateUserInfo, json.toString(), new RequestCallback() {
            @Override
            public void onFailure(Request request, Exception e) {
                e.printStackTrace();
                if (e instanceof RuntimeException) {
                    JUtils.Toast(e.getMessage());
                }
            }

            @Override
            public void onResponse(ResponceWrapper response) {
                if (HttpResponsHelper.SuccessResponce(response)) {
                    UserHelper.getInstance().updateUser(param, value);
                } else {
                    JUtils.Toast("修改失败");
                }
            }

            @Override
            public void onStart() {

            }
        }, "UPDATE_USERINFO");
    }

    void showStepPlanDialog() {
        ViewHolder contentViewHolder = new ViewHolder(getLayoutInflater().inflate(R.layout.dialog_set_setp_plan, null));
        View contentView = contentViewHolder.getInflatedView();
        WheelView wva = (WheelView) contentView.findViewById(R.id.main_wv);
        wva.setOffset(1);

        ArrayList<String> strings = new ArrayList<>();
        for (int i = 3000; i < 31000; i += 1000) {
            strings.add(i + "");
        }
        wva.setItems(strings);
        wva.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, String item) {
                step_plan = item;
            }
        });

        ViewHolder headerViewHolder = new ViewHolder(getLayoutInflater().inflate(R.layout.header, null));
        View headerView = headerViewHolder.getInflatedView();
        ((TextView) headerView.findViewById(R.id.tv_hint)).setText("设置每日步数:");

        ViewHolder footerViewHolder = new ViewHolder(getLayoutInflater().inflate(R.layout.footer, null));
        View footerView = footerViewHolder.getInflatedView();
        footerView.findViewById(R.id.al_footer).setBackgroundColor(Color.parseColor("#f4f4f4"));

        DialogPlus dialog = DialogPlus.newDialog(this)
                .setContentHolder(contentViewHolder)
                .setGravity(Gravity.CENTER)
                .setFooter(footerView)
                .setHeader(headerView)
                .setOnClickListener(this)
                .setInAnimation(R.anim.dialog_in_anim)
                .setOutAnimation(R.anim.dialog_out_anim)
                .create();

        dialog.show();
    }

    public void showStatureDialog() {
        ViewHolder contentViewHolder = new ViewHolder(getLayoutInflater().inflate(R.layout.dialog_user_weight, null));
        View contentView = contentViewHolder.getInflatedView();
        final TextView tv_value = (TextView) contentView.findViewById(R.id.tv_dialog_user_weight);
        ((XyzRuler) contentView.findViewById(R.id.ruler_weight)).setOnRulerValueChangeListener(new XyzRuler.RulerValue() {
            @Override
            public void value(int value) {
                tv_value.setText(value + "");
                user_weight = value + "";
            }
        });

        ViewHolder footerViewHolder = new ViewHolder(getLayoutInflater().inflate(R.layout.footer, null));
        View footerView = footerViewHolder.getInflatedView();
        footerView.findViewById(R.id.al_footer).setBackgroundColor(Color.parseColor("#f4f4f4"));
        DialogPlus dialog = DialogPlus.newDialog(this)
                .setContentHolder(contentViewHolder)
                .setGravity(Gravity.CENTER)
                .setFooter(footerView)
                .setOnClickListener(this)
                .setInAnimation(R.anim.dialog_in_anim)
                .setOutAnimation(R.anim.dialog_out_anim)
                .create();

        dialog.show();
    }

    public void showWeightDialog(OnClickListener listener) {
        ViewHolder contentViewHolder = new ViewHolder(getLayoutInflater().inflate(R.layout.dialog_user_stature, null));
        View contentView = contentViewHolder.getInflatedView();
        final TextView tv_value = (TextView) contentView.findViewById(R.id.tv_dialog_user_stature);
        ((XyzRuler) contentView.findViewById(R.id.ruler_stature)).setOnRulerValueChangeListener(new XyzRuler.RulerValue() {
            @Override
            public void value(int value) {
                tv_value.setText(value + "");
                user_stature = value + "";
            }
        });

        ViewHolder footerViewHolder = new ViewHolder(getLayoutInflater().inflate(R.layout.footer, null));
        View footerView = footerViewHolder.getInflatedView();
        footerView.findViewById(R.id.al_footer).setBackgroundColor(Color.parseColor("#f4f4f4"));
        DialogPlus dialog = DialogPlus.newDialog(this)
                .setContentHolder(contentViewHolder)
                .setGravity(Gravity.CENTER)
                .setFooter(footerView)
                .setOnClickListener(listener)
                .setInAnimation(R.anim.dialog_in_anim)
                .setOutAnimation(R.anim.dialog_out_anim)
                .create();

        dialog.show();
    }


    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void takeSuccess(TResult result) {
        TImage t = result.getImage();
        file = new File(t.getOriginalPath());
        uploadImg(file);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && resultCode == RESPONCECODE_CUSTOM_NICKNAME) {
            String nickname = data.getStringExtra("nickname");
            updateUserRequest("nickname", nickname);
            tv_name.setText(nickname);
        }
    }

    void uploadImg(final File file) {
        final File[] files = {file};
        final String[] filenames = {"file_upload"};
        try {
            OkHttpClientUtils.postUploadFilesAsync(this, URLConstants.FILE.FileUpload, files, filenames, new RequestCallback() {
                @Override
                public void onFailure(Request request, Exception e) {
                    e.printStackTrace();
                }

                @Override
                public void onResponse(ResponceWrapper response) {
                    String headerIco = response.getBody();
                    if (response.getResponcecode()==200&&!TextUtils.isEmpty(headerIco)) {
                        updateUserRequest("ico", response.getBody());

                        Glide.with(CustomPersonInfoActivity.this).load(file)
                                .placeholder(R.drawable.glide_place_holder)
                                .bitmapTransform(new CropCircleTransformation(CustomPersonInfoActivity.this))
                                .into(iv_head);
                    }
                }

                @Override
                public void onStart() {

                }
            }, "UPLOAD_USER_HEAD_IMG");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void takeFail(TResult result, String msg) {
        JUtils.Toast(msg);
    }

    @Override
    public void takeCancel() {
        JUtils.Log("选择取消");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }
}
